package project.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import project.DAO.volunteerDAO;
import project.DO.doctorDo;
import project.DO.volunteerDo;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
public class VolunteerController {
      @Autowired
    volunteerDAO volunteerDao;
      @RequestMapping("volunteer")
    public String volunteer(Map map)
      {
          List<volunteerDo> volunteerDoList;
          volunteerDoList= volunteerDao.selectAll();
          map.put("message",volunteerDoList);
          return "volunteer";
      }
      @RequestMapping("volunteer1")
    public  String volunteer1(HttpServletRequest request,MultipartFile file)
      {
              String name=request.getParameter("name");
              String telephone=request.getParameter("telephone");
              String sno=request.getParameter("sno");
              String affair=request.getParameter("affair");
              String area=request.getParameter("area");
              List<volunteerDo> volunteerDOList;
              if(request.getParameter("name")!=null)
              {
                  if(file.isEmpty())
                  {
                      return "volunteer";
                  }
                  //图片重命名,防止用户文件名相同导致图片覆盖
                  String originalFilename=file.getOriginalFilename();//原来的图片名
                  String ext="."+originalFilename.split("\\.")[1];//1.jpg,利于split来拆分得到后缀名
                  String uuid= UUID.randomUUID().toString().replace("-","");//通过uuid生成一个随机的名字，再toString转化，此时含有“-”，给他替换掉
                  String filename=uuid+ext;//重命名后的文件名
                  //上传图片
                  ApplicationHome applicationHome=new ApplicationHome(this.getClass());
                  String pre=applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath()+
                          "\\src\\main\\resources\\static\\volunteerPhoto\\";//获取到这个运行的程序的目录上级再上级，Dir获取到的是target下的classes
                  String path=pre+filename;//图片要上传的路径
                  try {
                      file.transferTo(new File((path)));
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
                  String photo="../static/volunteerPhoto/"+filename;//存储在数据库中的img的位置
                  volunteerDao.insertAll(photo,name,telephone,sno,affair,area);
              }
              return "forward:/volunteer";
          }
      }
